﻿@using Gurux.DLMS.AMI.Script
@using Gurux.DLMS.AMI.Shared.DIs

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Module
@using System.Globalization
@using System.Text
@using System.Text.Json
@using Gurux.DLMS.AMI.Script.Pages
@using Microsoft.Extensions.Logging

@attribute [Authorize(Roles = GXRoles.Admin + "," + GXRoles.Script)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier2 Notifier
@inject ILogger<ScriptView> _logger;

@if (Active != null)
{
    <EditForm Model="@Active">
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    <InputNullableSwitch Text="@Properties.Resources.Active" @bind-Value="Active.Active" />
                    <br />
                </div>
                <div class="form-group">
                    <InputCheckbox @bind-Value="Active.ServerSide" />
                    <label>@Properties.Resources.ServerSide</label>
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Name</label>
                    <InputText id="name" disabled="@IsDeleting" @bind-Value="Active.Name" class="form-control" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Description</label>
                    <InputText id="name" disabled="@IsDeleting" class="form-control"
                               @bind-Value="Active.Description" />
                </div>
                <ScriptEditor @bind-SourceCode="Active.SourceCode" @bind-SourceCode:event="ScriptChanged" />
                <button class="btn button" @onclick="OnValidate">
                    <div class="oi oi-flash"></div>
                    &nbsp;Validate
                </button>
                @if (Active.CreationTime != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.CreationTime</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="creationTime" readonly="readonly" class="form-control"
                           @bind-Value="Active.CreationTime" />
                    </div>
                }
                @if (Active.Updated != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Updated</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="updated" readonly="readonly" class="form-control"
                           @bind-Value="Active.Updated" />
                    </div>
                }
                @if (Active.Removed != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Removed</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="removed" class="form-control"
                           @bind-Value="Active.Removed" />
                    </div>
                }
                @if (action == CrudAction.Delete)
                {
                    <hr />
                    <p>
                    </p>
                    <div class="form-group">
                        <InputRadioGroup @bind-Value="DeleteTarget">
                            <InputRadio Value="false">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDisableQuestion</label><br>
                            <InputRadio Value="true">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDeleteQuestion</label>
                        </InputRadioGroup>
                        <br />
                    </div>
                }
            </div>
        </div>
    </EditForm>
}
@code {

    [CascadingParameter]
    private ScriptTab? Parent { get; set; }

    private GXScript? _active;

    private GXScript? Active
    {
        get
        {
            if (Parent?.Active != null)
            {
                return Parent.Active;
            }
            return _active;
        }
    }

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    private CrudAction action;
    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    private bool DeleteTarget;

    public string? IsDeleting
    {
        get
        {
            if (Notifier.Action != CrudAction.Delete)
            {
                return null;
            }
            return "disabled";
        }
    }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            if (Active == null && Id != null)
            {
                //Get script data.
                var tmp = (await Http.GetAsJsonAsync<GetScriptResponse>(string.Format("api/Script?id={0}", Id)));
                if (tmp?.Item != null)
                {
                    _active = tmp.Item;
                }
                else
                {
                    NavigationManager.NavigateTo("404");
                }
            }
            if (Active == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidTarget);
            }
            action = ClientHelpers.GetAction(Action); if (action == CrudAction.Delete)
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Remove, Icon = "oi oi-trash", OnClick = OnSave });
            }
            else
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            }
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Validate the script.
    /// </summary>
    public async void OnValidate()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (string.IsNullOrEmpty(Active?.SourceCode))
            {
                throw new Exception("No script to execute.");
            }
            ValidateScript req = new ValidateScript() { Script = Active.SourceCode };
            var ret = await Http.PostAsJson<ValidateScriptResponse>("api/Script/Validate", req);
            GXScriptException[]? errors = null;
            if (!string.IsNullOrEmpty(ret.Errors))
            {
                errors = JsonSerializer.Deserialize<GXScriptException[]>(ret.Errors);
            }
            if (errors != null)
            {
                Notifier?.ProcessErrors(errors);
            }
            else
            {
                Notifier?.ShowInformation(string.Format("Script build {0}. Build time: {1} ms.", DateTime.Now, ret.CompileTime));
            }
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Save script.
    /// </summary>
    public async void OnSave()
    {
        try
        {
            if (Active == null)
            {
                throw new Exception(Properties.Resources.InvalidTarget);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (action == CrudAction.Delete)
            {
                await Http.PostAsJson<RemoveScriptResponse>("api/Script/Delete", new RemoveScript()
                    {
                        Ids = new Guid[] { Active.Id },
                        Delete = DeleteTarget
                    });
            }
            else
            {
                string address;
                if (action == CrudAction.Create)
                {
                    address = "api/Script/Add";
                }
                else if (action == CrudAction.Update)
                {
                    address = "api/Script/Update";
                }
                else
                {
                    throw new Exception(Properties.Resources.InvalidTarget);
                }
                await Http.PostAsJson<UpdateScriptResponse>(address, new UpdateScript()
                    {
                        Scripts = new List<GXScript>() { Active }
                    });
            }
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Cancel update.
    ///</summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }
}
